
<!--
opts.name: 上传字段名 def 'file'
opts.disable: 上传是否可用
opts.multi: 允许多文件上传
opts.btn: 上传按钮文字
opts.auto: 选择文件后自动上传
opts.accept: 允许的文件格式
-->
<upload-formdata>
  <input if="{!disable}" type="file" onchange={fn.uploadOnChange} name={name} ref="fileInput" accept="{opts.accept}" multiple="{opts.multi||true}">
  <button show="{!opts.auto}" type="button" ref="btn" onclick={fn.upload} disabled="{disable}">{btnText}</button>
  <script>
    var tag = this;
    tag.name = opts.name || 'file';
    tag.btnText = opts.btn || '上传';
    tag.uploadFiles = [];
    tag.disable = opts.disable;
    tag.fn = {
      uploadOnChange: function(){
        if(opts.auto){
          tag.fn.upload(tag.refs.btn);
        }
      },
      upload: function(e) {
        tag.uploadFiles = tag.refs.fileInput.files;
        tag.progressList = [];
        if(!tag.uploadFiles.length){
          e.target.innerText = '请选择文件';
          return setTimeout(function(){
            e.target.innerText = tag.btnText;
          } ,1000);
        }
        var f = document.createElement('form');
        f.name = 'file';
        f.enctype = 'multipart/form-data';
        tag.fd = new FormData(f);
        for(var i=0; i < tag.uploadFiles.length; i++){
          tag.fd.append(tag.name, tag.uploadFiles[i]);
        }
        tag.emit('post', tag.fd);
      }
    };
    tag.on('mount', function(){
      // 浏览器支持检测
      if('FormData' in window === false){
        alert('浏览器不支持FormData!');
      }
    });
    tag.on('btn', function(text){
      tag.refs.btn.innerText = text;
    });
    tag.on('disable', function(flag){
      tag.disable = flag;
      tag.update();
    });
  </script>
</upload-formdata>
